package cn.jinjimi.app.custom.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import cn.jinjimi.base.Task.TaskExecutor;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.framework.helper.annotation.EventTrace;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.EventID;
import cn.jinjimi.app.bean.Permissions;
import cn.jinjimi.app.custom.entity.Custom;
import cn.jinjimi.app.custom.iview.InputCustomView;
import cn.jinjimi.app.custom.ui.adapter.CustomInputAdapter;
import cn.jinjimi.app.presenter.InputCustomPresent;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.dialog.LoadingDialog;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.widget.SideBar;
import cn.jinjimi.app.main.widget.XListView.XListView;

import java.util.ArrayList;
import java.util.List;

/**
 * Modify by Roy on 2015/11/09.
 * 导入客户
 */
public class CustomInputActivity extends ToolBarCommonActivity implements SideBar.OnTouchingLetterChangedListener
        , AdapterView.OnItemClickListener, InputCustomView {

    private XListView mListView = null;
    private CustomInputAdapter mAdapter = null;

    private TextView tvSelectNum;
    private CheckBox btnAllSelect;
    private Button btnComplete;
    private SideBar mSideBar;
    private List<Custom> mCustomList = new ArrayList<>();

    private InputCustomPresent mPresent = null;

    /**
     * 导入手机号码
     */
    public static void launch(Context context) {
        Intent intent = new Intent(context, CustomInputActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Permissions.checkPermissions(this, Permissions.REQUEST_CONTACTS_PERMISSIONS);
    }

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_inputcustom);
        setTitle(getString(R.string.title_add_custom));

        setSwipeEnabled(false);
    }

    @Override
    protected void initial() {
        initView();
        initListener();
        initData();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] results) {

        super.onRequestPermissionsResult(requestCode, permissions, results);
        Permissions.onRequestPermissionsResult(this, requestCode, permissions, results);
    }

    protected void initView() {
        mSideBar = (SideBar) findViewById(R.id.layout_sideBar);
        mListView = (XListView) findViewById(R.id.listview);
        mListView.setPullRefreshEnable(false);
        mListView.setPullLoadEnable(false);
        mListView.setTransparentBg();

        tvSelectNum = (TextView) findViewById(R.id.tv_select_num);
        btnAllSelect = (CheckBox) findViewById(R.id.cb_select);
        btnComplete = (Button) findViewById(R.id.btn_complete);

        mAdapter = new CustomInputAdapter(this);
        mListView.setAdapter(mAdapter);

        updateBottomBarState();
    }

    protected void initListener() {
        btnComplete.setOnClickListener(this);
        btnAllSelect.setOnClickListener(this);
        mListView.setOnItemClickListener(this);
        mSideBar.setOnTouchingLetterChangedListener(this);
    }

    protected void initData() {
        showLoadingIndicator();
        mPresent = new InputCustomPresent(this, CustomInputActivity.this);
        mPresent.getCustoms();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_complete:  // 导入按钮
                clickComplete();
                break;
            case R.id.cb_select:  //全选
                mAdapter.setAllSelect(btnAllSelect.isChecked());
                updateBottomBarState();
                break;
        }
    }

    @EventTrace(EventID.APP_CUSTOM_ADD_CHOSE)
    private void clickComplete() {
        mPresent.upLoad(mAdapter.getSelectedCustoms());
    }

    @Override
    public void finish() {
        if (mAdapter != null && mAdapter.getSelectedCustoms().size() > 0) {
            cancelEditAlert();
        } else
            super.finish();

    }

    public void cancelEditAlert() {
        getAlertDialog()
                .setTitle("确定要放弃从通讯录导入客户?")
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                        mAdapter = null;
                        //直接退到添加客户Activity
                        finish();
                    }
                });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.TWO_BUTTON);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mAdapter.onItemClick(position - mListView.getHeaderViewsCount(), view);
        updateBottomBarState();

    }

    /* 上传成功 */
    @Override
    public void uploadSuccess() {
        mAdapter = null;
        setResult(RESULT_OK);
        super.finish();
    }

    @Override
    public void getCustomSucc(final List<Custom> customs) {
        TaskExecutor.runTaskOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAdapter.setItems(customs);
                mCustomList = customs;
                updateBottomBarState();
                hideLoadingIndicator();
                updateIndexFlag(customs);

                btnAllSelect.setChecked(true);
                mAdapter.setAllSelect(btnAllSelect.isChecked());
                updateBottomBarState();
            }
        });
    }

    /**
     * 更新右侧字母索引
     *
     * @param customers
     */
    private void updateIndexFlag(List<Custom> customers) {
        if (customers == null || customers.isEmpty()) {
            mSideBar.setVisibility(View.GONE);
            return;
        }

        List<String> indexFlag = new ArrayList<>();
        String[] chars = new String[indexFlag.size()];
        mSideBar.setIndexChars(indexFlag.toArray(chars));
        mSideBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void loading() {
    }

    @Override
    public void loadSucc() {
    }

    @Override
    public void loadFail() {
        LoadingDialog.dispose();
        CommAlertDialog alert = getAlertDialog()
                .setTitleAndMessage(getString(R.string.upload_contacts_load_fail_title), getString(R.string.upload_contacts_load_fail_msg));
        alert.showDialog(CommAlertDialog.Style.ONE_BUTTON);
    }

    @Override
    public void showToast(int resId) {
        ToastUtils.toastMessage(CustomInputActivity.this, getResources().getString(resId));
    }

    /* 更新下面bottomBar的状态 */
    private void updateBottomBarState() {
        tvSelectNum.setText(String.format(getString(R.string.have_pick_num), mAdapter.getSelectedCustoms().size()));
        btnComplete.setEnabled(mAdapter.getSelectedCustoms().size() > 0);
        btnAllSelect.setChecked(mAdapter.getSelectedCustoms().size() >= mAdapter.getSelecteableCustoms().size());// 判断是否全选
        btnAllSelect.setEnabled(mAdapter.getSelecteableCustoms().size() != 0);  //判断可否全选
    }

    @Override
    public void onTouchingLetterChanged(String s) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPresent.onDestroy();
    }
}